package com.ityuwen.mengyagushi.common.login;

import com.ityuwen.mengyagushi.common.constant.RedisConstant;
import com.ityuwen.mengyagushi.common.execption.GuiguException;
import com.ityuwen.mengyagushi.common.result.ResultCodeEnum;
import com.ityuwen.mengyagushi.common.util.AuthContextHolder;
import com.ityuwen.mengyagushi.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class GuiGuLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Around("@annotation(guiGuLogin)")
    public Object around(ProceedingJoinPoint joinPoint, GuiGuLogin guiGuLogin) throws Throwable {

        /// 身份认证
        ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (sra == null){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        HttpServletRequest request = sra.getRequest();
        // 从请求对象中获取token
        String token = request.getHeader("token");
        UserInfoVo userInfoVo = null;
        if (StringUtils.isNotBlank(token)){
            userInfoVo = (UserInfoVo)this.redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        }
        // 去登录：必须登录 并且token或者userInfoVo
        if (guiGuLogin.required() && (StringUtils.isBlank(token) || userInfoVo == null)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        // 通过threadLocal传递给后续业务
        if (userInfoVo != null){
            AuthContextHolder.setUserId(userInfoVo.getId());
            AuthContextHolder.setUsername(AuthContextHolder.getUsername());
        }

        // 执行目标方法
        Object result = joinPoint.proceed(joinPoint.getArgs());

        // 释放ThreadLocal，防止内存泄漏
        AuthContextHolder.removeUserId();
        AuthContextHolder.removeUsername();

        return result;
    }
}
